package utils

import (
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"strings"
	"less_day/internal/config"
)

type WechatAccessToken struct {
	AccessToken string `json:"access_token"`
	ExpiresIn   int    `json:"expires_in"`
	OpenID      string `json:"openid"`
	UnionID     string `json:"unionid"`
	ErrCode     int    `json:"errcode"`
	ErrMsg      string `json:"errmsg"`
}

type WechatPhoneInfo struct {
	PhoneInfo struct {
		PhoneNumber     string `json:"phoneNumber"`
		PurePhoneNumber string `json:"purePhoneNumber"`
		CountryCode     string `json:"countryCode"`
		Watermark       struct {
			Timestamp int64  `json:"timestamp"`
			AppID     string `json:"appid"`
		} `json:"watermark"`
	} `json:"phone_info"`
	ErrCode int    `json:"errcode"`
	ErrMsg  string `json:"errmsg"`
}

func GetWechatOpenID(code string) (string, error) {
	cfg, err := config.LoadConfig()
	if err != nil {
		return "", err
	}
	
	url := fmt.Sprintf("https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code",
		cfg.Wechat.AppID, cfg.Wechat.Secret, code)
	
	resp, err := http.Get(url)
	if err != nil {
		return "", err
	}
	defer resp.Body.Close()
	
	body, err := io.ReadAll(resp.Body)
	if err != nil {
		return "", err
	}
	
	var result WechatAccessToken
	if err := json.Unmarshal(body, &result); err != nil {
		return "", err
	}
	
	if result.ErrCode != 0 {
		return "", fmt.Errorf("wechat error: %s", result.ErrMsg)
	}
	
	return result.OpenID, nil
}

func GetWechatPhoneNumber(accessToken, code string) (string, error) {
	url := fmt.Sprintf("https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=%s", accessToken)
	
	requestBody := fmt.Sprintf(`{"code":"%s"}`, code)
	
	resp, err := http.Post(url, "application/json", strings.NewReader(requestBody))
	if err != nil {
		return "", err
	}
	defer resp.Body.Close()
	
	body, err := io.ReadAll(resp.Body)
	if err != nil {
		return "", err
	}
	
	var result WechatPhoneInfo
	if err := json.Unmarshal(body, &result); err != nil {
		return "", err
	}
	
	if result.ErrCode != 0 {
		return "", fmt.Errorf("wechat error: %s", result.ErrMsg)
	}
	
	return result.PhoneInfo.PhoneNumber, nil
}